<template>
  <div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="150px"
      @submit.native.prevent
      :show-message="false"
      :validate-on-rule-change="false"
    >
      <el-row>
        <div v-for="(item, index) in addform" :key="index">
          <el-col
            :span="item.abreast ? 11 : 24"
            v-if="item.status == '1' && isShow(item)"
            :style="
              item.componentType &&
              (item.componentType.indexOf('file') > -1 ||
                item.componentType.indexOf('image') > -1 ||
                item.componentType.indexOf('textarea') > -1)
                ? ''
                : 'height:37px;'
            "
          >
            <el-form-item
              :label="item.name"
              :prop="item.prop"
              :required="
                item.componentType == 'el-input-auto'
                  ? !auto && item.required
                  : item.required
              "
            >
              <!--根据componentType来显示是什么标签-->
              <!--输入框-->
              <el-input
                v-if="item.componentType === 'el-input'"
                size="small"
                style="width: 100%"
                v-model="form[item.prop]"
                :disabled="!item.editable"
                :placeholder="item.placeholder"
              >
              </el-input>
              <template v-else-if="item.componentType === 'el-input-auto'">
                <el-input
                  size="small"
                  style="width: 80%"
                  v-model="form[item.prop]"
                  :disabled="auto || !item.editable"
                  :placeholder="item.placeholder"
                  :required="!auto"
                >
                </el-input>
                <el-checkbox
                  style="width: 15%; float: right"
                  v-model="auto"
                  @change="handleAuto(item.prop)"
                  >自动
                </el-checkbox>
              </template>
              <el-input
                v-else-if="item.componentType === 'el-textarea'"
                type="textarea"
                size="small"
                style="width: 100%"
                v-model="form[item.prop]"
                :disabled="!item.editable"
                rows="3"
                :placeholder="item.placeholder"
                :maxlength="item.optionValue"
                show-word-limit
              >
              </el-input>
              <!--选择框-->
              <el-select
                size="small"
                style="width: 100%"
                v-model="form[item.prop]"
                placeholder="请选择"
                clearable
                filterable
                v-else-if="item.componentType === 'el-select'"
                @change="handleSelectChange(item.prop)"
                :disabled="!item.editable"
              >
                <el-option
                  v-for="dict in item.optionValue"
                  :key="dict.id"
                  :label="
                    dict.systemName || !dict.name ? dict.description : dict.name
                  "
                  :value="
                    typeof form[item.prop] == 'number'
                      ? Number(dict.id)
                      : String(dict.id)
                  "
                >
                </el-option>
              </el-select>
              <!--多选 选择框-->
              <el-select
                multiple
                size="small"
                style="width: 100%"
                v-model="form[item.prop]"
                placeholder="请选择"
                v-else-if="item.componentType === 'el-selects'"
                @change="handleSelectChange"
                :disabled="!item.editable"
                filterable
              >
                <el-option
                  v-for="dict in item.optionValue"
                  :key="dict.id"
                  :label="
                    dict.systemName || !dict.name ? dict.description : dict.name
                  "
                  :value="dict.id"
                >
                </el-option>
              </el-select>
              <!--添加现有项-->
              <template v-else-if="item.componentType === 'el-add-existing'">
                <el-select
                  size="small"
                  style="width: calc(95% - 50px);height:100%"
                  v-model="form[item.prop]"
                  placeholder="请选择"
                  :disabled="true"
                  filterable
                >
                  <template
                    v-if="
                      item.optionValue instanceof Array &&
                        item.optionValue.length > 0
                    "
                  >
                    <el-option
                      v-for="dict in item.optionValue"
                      :key="dict.id"
                      :label="dict.name || dict.folderName"
                      :value="String(dict.id)"
                    >
                    </el-option>
                  </template>
                </el-select>
                <el-button
                  style="width: 50px; margin: 5px 0;float: right"
                  size="mini"
                  :disabled="!item.editable"
                  @click="addExisting(item)"
                >
                  选择
                </el-button>
              </template>
              <!--级联选择器-->
              <el-cascader
                size="small"
                style="width: 100%"
                v-else-if="item.componentType === 'el-cascader'"
                v-model="form[item.prop]"
                :options="item.optionValue"
                :disabled="!item.editable"
                :props="{ expandTrigger: 'hover', emitPath: false }"
              >
              </el-cascader>
              <!--日期-->
              <el-date-picker
                v-model="form[item.prop]"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择日期"
                clearable
                v-else-if="item.componentType === 'el-date-picker'"
                :picker-options="
                  form.id == undefined && item.optionValue ? pickerOptions : ''
                "
              >
              </el-date-picker>
              <!-- 年月 -->
              <el-date-picker
                v-model="form[item.prop]"
                format="yyyy-MM"
                value-format="yyyy-MM"
                placeholder="请选择年月"
                clearable
                v-else-if="item.componentType === 'el-month-picker'"
                type="month"
                :picker-options="
                  form.id == undefined && item.optionValue ? pickerOptions : ''
                "
              >
              </el-date-picker>
              <el-time-picker
                v-model="form[item.prop]"
                :picker-options="{
                  selectableRange: '08:00:00 - 22:00:00'
                }"
                v-else-if="item.componentType === 'el-time-picker'"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
              >
              </el-time-picker>
              <!--多选日期-->
              <el-date-picker
                style="width: 100%"
                type="dates"
                v-model="form[item.prop]"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择日期"
                clearable
                v-else-if="item.componentType === 'el-dates-picker'"
              >
              </el-date-picker>
              <!--日期范围-->
              <el-date-picker
                style="width: 100%"
                v-model="
                  form[item.prop] ? form[item.prop].split(',') : form[item.prop]
                "
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                v-else-if="item.componentType === 'el-dates-daterange'"
              >
              </el-date-picker>
              <!--单选框-->
              <el-radio-group
                v-model="form[item.prop]"
                :disabled="!item.editable"
                v-else-if="item.componentType === 'el-radio'"
              >
                <el-radio
                  v-for="dict in item.optionValue"
                  :key="dict.id"
                  :label="
                    typeof form[item.prop] == 'string'
                      ? dict.id
                      : Number(dict.id)
                  "
                  >{{ dict.description }}
                </el-radio>
              </el-radio-group>
              <!--多选框-->
              <div v-else-if="item.componentType === 'el-checkbox-group'">
                <div style="margin-left: 20px">文档名称</div>
                <el-checkbox-group
                  :disabled="!item.editable"
                  v-model="docIds"
                  style="max-height: 300px"
                >
                  <el-checkbox
                    style="display: block"
                    v-for="val in item.optionValue"
                    :label="Number(val.id)"
                    :key="val.id"
                    >{{ val.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <!-- 评分 -->
              <el-rate
                v-else-if="item.componentType === 'el-rate'"
                style="margin-top: 10px"
                v-model="form[item.prop]"
                show-score
                :disabled="!item.editable"
                text-color="#ff9900"
              >
              </el-rate>
              <!--文件上传组件-->
              <el-upload
                ref="fileList"
                class="upload-file-uploader"
                :action="upload.url"
                :before-upload="handleFileBeforeUpload"
                :file-list="fileListFormat(form[item.prop])"
                multiple
                :on-progress="handleFileUploadProgress"
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                :on-success="
                  (response, file, fileList) =>
                    handleFileSuccess(response, file, fileList, item.prop)
                "
                :on-remove="
                  (file, fileList) =>
                    handleFileRemove(file, fileList, item.prop)
                "
                :headers="upload.headers"
                v-else-if="item.componentType === 'el-file'"
              >
                <el-button size="small" type="primary" icon="el-icon-upload"
                  >点击上传
                </el-button>
              </el-upload>
              <!--单文件上传-->
              <el-upload
                ref="fileList"
                class="upload-file-uploader"
                :action="upload.url"
                :before-upload="handleFileBeforeUpload"
                :file-list="fileListFormat(form[item.prop])"
                :on-progress="handleFileUploadProgress"
                :on-error="handleUploadError"
                :limit="1"
                :on-exceed="handleExceed"
                :on-success="
                  (response, file, fileList) =>
                    handleFileSuccess(response, file, fileList, item.prop)
                "
                :on-remove="
                  (file, fileList) =>
                    handleFileRemove(file, fileList, item.prop)
                "
                :headers="upload.headers"
                v-else-if="item.componentType === 'file'"
              >
                <el-button size="small" type="primary" icon="el-icon-upload"
                  >点击上传
                </el-button>
              </el-upload>
              <div v-else-if="item.componentType === 'image'">
                <div
                  class="pasteImg"
                  @mouseenter="ready = true"
                  @mouseleave="ready = false"
                  onClick="attachFile.click()"
                  contentEditable="true"
                  @dragenter="drag($event)"
                  @dragover="drag($event)"
                  @drop="dragEnd($event)"
                >
                  <div
                    contenteditable
                    style="
                      width: 100%;
                      height: 100%;
                      position: absolute;
                      opacity: 0;
                      z-index: 100;
                    "
                  ></div>
                  右键粘贴/Ctrl+V上传图片
                </div>
                <input
                  type="file"
                  name="attachFile"
                  id="attachFile"
                  style="display: none"
                  accept="image/*"
                  multiple
                  @change="handleImageChange($event)"
                />
                <template
                  v-if="
                    form[item.prop] && JSON.parse(form[item.prop]).length > 0
                  "
                >
                  <div
                    style="
                      width: 100px;
                      height: 47px;
                      background: grey;
                      text-align: center;
                      float: left;
                      margin-left: 20px;
                      position: relative;
                    "
                    v-for="(img, index) of JSON.parse(form[item.prop])"
                    :key="index"
                  >
                    <img
                      style="width: 100%; height: 100%"
                      :src="img.path"
                      @click="
                        imgPreview(
                          JSON.parse(form[item.prop])
                            .map(item => item.path)
                            .concat(imageSrc)
                        )
                      "
                    />
                    <i
                      class="el-icon-error"
                      style="position: absolute; top: 0; right: 0"
                      @click="removeImg(img, index, item.prop)"
                    ></i>
                  </div>
                </template>

                <template v-if="imageSrc.length > 0">
                  <div
                    style="
                      width: 100px;
                      height: 47px;
                      background: grey;
                      text-align: center;
                      float: left;
                      margin-left: 20px;
                      position: relative;
                    "
                    v-for="(item, index) of imageSrc"
                    :key="'b64' + index"
                  >
                    <img
                      style="width: 100%; height: 100%"
                      :src="item"
                      @click="
                        imgPreview(
                          JSON.parse(form[item.prop])
                            .map(item => item.path)
                            .concat(imageSrc)
                        )
                      "
                    />
                    <i
                      class="el-icon-error"
                      style="position: absolute; top: 0; right: 0"
                      @click="removeB64(index)"
                    ></i>
                  </div>
                </template>
              </div>
              <el-input
                size="small"
                style="width: 100%"
                :disabled="!item.editable"
                v-model="form[item.prop]"
                v-else
              >
              </el-input>
            </el-form-item>
          </el-col>
        </div>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        @click="apply"
        v-if="
          form.id == undefined &&
            addform[0] &&
            addform[0].prop == 'typeid' &&
            addform[0].optionValue[0].label == 'WBS'
        "
        >应 用
      </el-button>
      <el-button type="primary" @click="submitForm" v-preventReClick
        >确 定</el-button
      >
      <el-button @click="cancel">取 消</el-button>
    </div>
    <el-dialog
      ref="formTable"
      :title="title"
      :visible.sync="topen"
      width="80%"
      v-dialogDrag
      append-to-body
      :close-on-click-modal="false"
      v-if="topen"
    >
      <dynamic-form-table
        ref="addFormTable"
        :geturl="geturl"
        @topenChanged="topenChanged"
        @submit="handleSubmitAddExisting"
        :table="table"
        :formtype="formtype"
        :search="search"
        :formMulti="formMulti"
        :defaultSelect="defaultSelect"
        :expandUrl="expandUrl"
      >
      </dynamic-form-table>
    </el-dialog>
    <!-- 图片上传进度显示 -->
    <el-dialog
      ref="uploadProgress"
      title="图片上传进度"
      :visible.sync="uploadProgressOpen"
      width="50%"
      v-dialogDrag
      append-to-body
      :close-on-click-modal="false"
      v-if="uploadProgressOpen"
    >
      <div style="height:30px;width:100%">
        <!-- <span class="right btn">重命名</span> -->
        <el-button class="right btn" @click="reName = true" v-if="!reName"
          >重命名</el-button
        >
        <template v-else>
          <el-button class="right btn" @click="handleReset">重置</el-button>
          <el-button class="right btn" @click="handleCancelRename"
            >取消</el-button
          >
          <!-- <el-button class="right btn" @click="reName=false">确定</el-button> -->
        </template>
      </div>
      <div v-for="(item, index) in image" :key="index" style="padding:5px">
        <span v-if="!reName">{{ fileNameList[index] }}:</span>
        <el-input
          v-else
          v-model="fileNameList[index]"
          style="width:300px"
        ></el-input>
        <el-popover
          placement="top-start"
          width="200"
          title="详细信息"
          trigger="click"
        >
          <div>
            <span class="detail-title">文件名称:</span
            ><span class="detail-content">{{ item.name }}</span>
          </div>
          <div>
            <span class="detail-title">文件类型:</span
            ><span class="detail-content">{{ item.type }}</span>
          </div>
          <div>
            <span class="detail-title">文件大小:</span
            ><span class="detail-content">{{ formatSize(item.size) }}</span>
          </div>
          <div>
            <span class="detail-title">最近修改时间:</span
            ><span class="detail-content">{{
              dayjs(item.lastModifiedDate).format('YYYY/MM/DD HH:mm:ss')
            }}</span>
          </div>
          <el-button class="right btn" slot="reference">详细信息</el-button>
        </el-popover>
        <el-progress :percentage="100"></el-progress>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="
            uploadProgressOpen = false
            reName = false
          "
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { deepClone, filter2sub, createUniqueString, formatSize } from '@/utils'
import {
  addData,
  updateData,
  getDataList,
  filedel,
  baseRequest
} from '@/api/dynamic/dynamic'
import axios from 'axios'
import dayjs from 'dayjs'
import { uploadObj } from '@/settings.js'
export default {
  name: 'dynamicForm',
  inject: ['app'],
  props: {
    inline: Boolean,
    form: {
      type: Object,
      default: {}
    },
    addform: Array,
    rules: Object,
    addurl: String
  },
  components: {
    dynamicFormTable: () => import('@/views/components/dynamicFormTable')
  },
  data() {
    return {
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/common/upload",
        url: uploadObj.upload,
        // 上传的文件列表
        showFileList: [],
        // 大小限制(MB)
        fileSize: 500
      },
      docIds: [],
      copy_form: {},
      auto: true,
      ready: false,
      image: [],
      imageSrc: [],
      hasUploadFile: [],
      hasapply: false,
      // 设置只能选择当前日期及之后的日期
      pickerOptions: {
        disabledDate(time) {
          //如果没有后面的-8.64e7就是不可以选择今天的
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      current: null,
      topen: false,
      geturl: '',
      formMulti: 'false',
      search: 'full_search',
      table: 'table',
      formtype: '',
      defaultSelect: {},
      title: '',
      expandUrl: '',
      uploadProgressOpen: false,
      contextmenu: {
        visible: false,
        left: 0,
        top: 0
      },
      reName: false,
      fileNameList: [],
      copyFileNameList: []
    }
  },
  mounted() {
    document.addEventListener('paste', this.onPasteUpload)
    // let dropBox = document.getElementById()
    // dropBox.addEventListener('dragover',)
    setTimeout(() => {
      this.selectChange(this.form.policyid)
      this.handleChange(this.form.typeid)
    }, 500)
    this.dayjs = dayjs
    this.formatSize = formatSize
  },
  destroyed() {
    document.removeEventListener('paste', this.onPasteUpload)
  },
  deactivated() {
    document.removeEventListener('paste', this.onPasteUpload)
  },
  watch: {
    'form.id': {
      deep: true,
      immediate: true,
      handler: function(newV, oldV) {
        if (newV != undefined) {
          this.copy_form = deepClone(this.form)
        }
      }
    },
    'form.typeid': {
      deep: true,
      immediate: true,
      handler: function(newV, oldV) {
        if (newV != undefined && newV != oldV) {
          this.handleChange(newV, oldV)
        }
      }
    },
    'form.policyid': {
      deep: true,
      immediate: true,
      handler: function(newV, oldV) {
        if (newV != undefined && newV != oldV) {
          this.selectChange(newV, oldV)
        }
      }
    }
  },
  methods: {
    handleFileBeforeUpload(file) {
      // 校检文件大小
      if (this.upload.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.upload.fileSize
        if (!isLt) {
          this.msgError(`上传文件大小不能超过 ${this.upload.fileSize} MB!`)
          return false
        }
      }
      if (this.form.fileList) {
        if (
          this.form.fileList.filter(item => item.fileName == file.name).length >
          0
        ) {
          this.msgInfo('该文件已上传')
          return false
        }
      }
      return true
    },
    // 文件个数超出
    handleExceed() {
      this.msgError(`文件个数超出限制`)
    },
    // 上传失败
    handleUploadError(err) {
      this.msgError('上传失败, 请重试')
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList, prop) {
      this.upload.isUploading = false
      if (response.code == 200) {
        if (!this.form[prop]) {
          this.form[prop] = []
        }
        this.form[prop].push({
          fileName: file.name,
          path: response.fileName,
          fileSize: file.size
        })
        this.hasUploadFile.push(prop)
        this.msgSuccess(response.msg)
      } else {
        this.$refs.fileList[0].uploadFiles = fileList.filter(
          item => item.uid != file.uid
        )
        this.msgError(response.msg)
      }
    },
    handleFileRemove(file, fileList, prop) {
      fileList = this.form[prop].filter(item => item.fileName == file.name)
      this.form[prop] = this.form[prop].filter(
        item => item.fileName != file.name
      )
      filedel({ fileList: fileList }).then(response => {
        this.msgSuccess('已删除')
      })
    },
    fileListFormat(list) {
      if (list && list.length != this.upload.showFileList.length) {
        this.upload.showFileList = list.map(item => {
          return {
            name: item.fileName,
            url: item.path
          }
        })
      }
      return this.upload.showFileList
    },
    handleAuto(prop) {
      // console.log(prop,this.form[prop])
      if (this.form[prop]) this.form[prop] = undefined
    },
    getOptionsData() {
      let optionData = JSON.parse(sessionStorage.getItem('optionsData'))
      this.addform.forEach((item, index) => {
        if (item.componentType === 'el-select') {
          this.addform[index].optionValue = optionData[item.optionValue]
        }
        if (item.componentType === 'el-cascader') {
          let optionarr = item.optionValue.split('?')
          if (optionarr.length > 1) {
            let typearr = []
            optionData[optionarr[0]].forEach(titem => {
              if (titem.value === parseInt(optionarr[1])) {
                typearr.push(titem)
                this.addform[index].optionValue = typearr
              }
            })
          } else {
            this.addform[index].optionValue = this.normalizer(
              optionData[item.optionValue]
            )
          }
        }
        if (item.componentType === 'el-checkbox-group') {
          getDataList(item.optionValue, {}).then(response => {
            this.addform[index].optionValue = []
            this.addform[index].optionValue = response.rows
          })
        }
      })
    },
    /** 转换数据结构 */
    normalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          value: item.id,
          label: item.description,
          parentid: item.parentid
        }
      })
      return this.handleTree(data, 'value')
    },
    /** 转换选项数据结构 */
    selectNormalizer(data) {
      data.forEach((item, index) => {
        data[index] = {
          id: item.dictValue,
          description: item.dictLabel
        }
      })
      return data
    },
    // 取消按钮
    cancel() {
      // if (this.hasUploadFile.length>0) {
      //   for(let item of this.hasUploadFile){
      //     let filelist = this.copy_form[item]
      //       ? this.form[item].slice(this.copy_form[item].length)
      //       : this.form[item].slice();
      //     filedel({ fileList: filelist }).then((response) => {
      //       this.$emit("openChanged", this.hasapply);
      //     });
      //   }
      // } else this.$emit("openChanged", this.hasapply);
      this.$emit('openChanged', this.hasapply)
    },
    isShow(item) {
      if (item.show && String(item.show).indexOf('$') > -1) {
        return this.dynamicEval(this.form, item.show)
      } else {
        return true
      }
    },
    /** 提交按钮 */
    submitForm() {
      // console.log(this.form);return
      var route = this.addurl
      if (route) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.$emit('loadingOpen')
            if (this.docIds.length > 0) {
              this.form.docIds = this.docIds.join(',')
            }
            if (this.form.id != undefined) {
              if (this.imageSrc.length > 0) {
                const baseUrl = this.upload.url
                // for (let item of this.image) {
                //   formData.append("file[]", item, item.fileName);
                // }
                let prop = this.addform.filter(
                  item => item.componentType === 'image'
                )[0].prop
                this.form[prop] = this.form[prop]
                  ? JSON.parse(this.form[prop])
                  : []
                for (let index in this.image) {
                  let formData = new FormData()
                  let item = this.image[index]
                  formData.append('file', item, item.fileName)
                  axios
                    .post(baseUrl, formData, {
                      responseType: 'json',
                      headers: {
                        Authorization: 'Bearer ' + getToken(),
                        'Content-Type': 'multipart/form-data'
                      }
                    })
                    .then(response => {
                      this.form[prop].push({
                        fileName: this.fileNameList[index],
                        path: response.data.fileName,
                        fileSize: item.size
                      })
                      if (index == this.image.length - 1) {
                        this.form[prop] = JSON.stringify(this.form[prop])
                        updateData(route, this.form)
                          .then(response => {
                            if (response.code === 200) {
                              this.msgSuccess('修改成功')
                              this.$emit('openChanged', true)
                            }
                          })
                          .catch(reject => {
                            this.$emit('loadingClose')
                          })
                      }
                    })
                }
                // axios
                //   .post(baseUrl, formData, {
                //     responseType: "json",
                //     headers: {
                //       Authorization: "Bearer " + getToken(),
                //       "Content-Type": "multipart/form-data",
                //     },
                //   })
                //   .then((response) => {
                //     if (response.data.code == 200) {
                //       this.form.thumb = response.data.fileName;
                //       updateData(route, this.form).then((response) => {
                //         if (response.code === 200) {
                //           this.msgSuccess("修改成功");
                //           this.$emit("openChanged", true);
                //         }
                //       });
                //     }
                //   });
              } else {
                let keys = this.addform.map(item => {
                  return item.prop
                })
                let subData = filter2sub(keys, [this.form], [this.copy_form])
                if (subData.length == 0 && !this.hasUploadFile) {
                  this.msgInfo('未修改任何数据')
                  this.cancel()
                  return
                }
                updateData(route, this.form)
                  .then(response => {
                    if (response.code === 200) {
                      this.msgSuccess('修改成功')
                      this.$emit('openChanged', true)
                    }
                  })
                  .catch(reject => {
                    this.$emit('loadingClose')
                  })
              }
            } else {
              if (this.imageSrc.length > 0) {
                const baseUrl = this.upload.url
                let prop = this.addform.filter(
                  item => item.componentType === 'image'
                )[0].prop
                this.form[prop] = []
                // this.uploadProgress=this.image.mag(item={return {}})
                // for (let item of this.image) {
                //   this.uploadProgress[item.fileName] = {fileName:item.fileName,process:0}
                // }
                // this.uploadProgressOpen = true
                for (let index in this.image) {
                  let formData = new FormData()
                  let item = this.image[index]
                  formData.append('file', item, item.name)
                  axios
                    .post(baseUrl, formData, {
                      responseType: 'json',
                      headers: {
                        Authorization: 'Bearer ' + getToken(),
                        'Content-Type': 'multipart/form-data'
                      }
                      // onUploadProgress: (e)=>{
                      //   let process = e.loaded/e.total*100 | 0
                      //   this.uploadProgress[item.fileName].process = process
                      // }
                    })
                    .then(response => {
                      this.form[prop].push({
                        fileName: item.name,
                        path: response.data.fileName,
                        fileSize: item.size
                      })
                      if (index == this.image.length - 1) {
                        this.form[prop] = JSON.stringify(this.form[prop])
                        addData(route, this.form)
                          .then(response => {
                            if (response.code === 200) {
                              this.msgSuccess('新增成功')
                              this.$emit('openChanged', true)
                            }
                          })
                          .catch(reject => {
                            this.$emit('loadingClose')
                          })
                      }
                    })
                }
                // axios
                //   .post(baseUrl, formData, {
                //     responseType: "json",
                //     headers: {
                //       Authorization: "Bearer " + getToken(),
                //       "Content-Type": "multipart/form-data",
                //     },
                //   })
                //   .then((response) => {
                //     if (response.data.code == 200) {
                //       this.form.thumb = response.data.fileName;
                //       addData(route, this.form).then((response) => {
                //         if (response.code === 200) {
                //           this.msgSuccess("新增成功");
                //           this.$emit("openChanged", true);
                //         }
                //       });
                //     }
                //   });
              } else {
                if (route.indexOf('enovia') > -1) {
                  // console.log(this.form)
                  let subData = {}
                  if (route.indexOf('basic') > -1) {
                    subData = {
                      parentId: this.form.pmsid,
                      loginUser:
                        sessionStorage.getItem('loginUser') ||
                        this.$store.state.user.userid,
                      // type: optionsData['typeOptions'].filter(item=>item.id==this.form.typeid)[0].name,
                      // policy: optionsData['policyOptions'].filter(item=>item.id==this.form.policyid)[0].name,
                      // name: this.form.name,
                      // title: this.form.title,
                      // code: this.form.code,
                      // fileList: this.form.fileList,
                      relationship: '',
                      ...this.form
                    }
                  } else {
                    this.form.loginUser =
                      sessionStorage.getItem('loginUser') ||
                      this.$store.state.user.userid
                    // this.form.type=optionsData['typeOptions'].filter(item=>item.id==this.form.typeid)[0].name;
                    // this.form.policy= optionsData['policyOptions'].filter(item=>item.id==this.form.policyid)[0].name;
                    subData = deepClone(this.form)
                    // subData.loginUser=sessionStorage.getItem('loginUser')||this.$store.state.user.userid;
                  }
                  // console.log(subData,this.form);return
                  addData(route, subData)
                    .then(response => {
                      response = JSON.parse(response)
                      // console.log(response)
                      if (response.code == 0) {
                        if (route.indexOf('basic') > -1) {
                          addData('/deliverable/addPLMDeliverable', {
                            ids: response.id,
                            projectid: this.form.projectid,
                            pmsid: this.form.pmsid
                          }).then(res => {
                            if (res.code == 200) {
                              this.msgSuccess('新增成功')
                              this.$emit('openChanged', true)
                            }
                          })
                        } else {
                          this.msgSuccess('新增成功')
                          this.$emit('openChanged', true)
                        }
                      } else {
                        this.msgError(response.msg)
                        this.$emit('loadingClose')
                      }
                    })
                    .catch(error => {
                      // this.msgError(response.msg);
                      this.$emit('loadingClose')
                    })
                } else if (route.indexOf('Windchill') > -1) {
                  // console.log(this.form)
                  let subData = {
                    id: '',
                    type: '',
                    number: '',
                    name: '',
                    description: '',
                    owner: '',
                    originated: '',
                    revision: '',
                    version: '',
                    status: '',
                    primary: {},
                    attachments: [],
                    ibaMap: {}
                  }
                  let primary = this.form['primary']
                    ? this.form['primary'][0]
                    : {}
                  delete this.form['primary']
                  let nextSub = deepClone(this.form)
                  delete this.form['parentid']
                  delete this.form['pmsid']
                  delete this.form['projectid']
                  subData = {
                    ...subData,
                    primary,
                    ...this.form
                  }
                  // console.log(subData);
                  // return
                  baseRequest('/pms' + route, 'post', {}, subData, {
                    isToken: true,
                    Authorization: 'Basic d2NhZG1pbjp3Y2FkbWlu'
                  })
                    .then(response => {
                      // response = JSON.parse(response)
                      // console.log(response)
                      if (response.code == 0) {
                        addData('/deliverable/addWCDeliverable', {
                          ids: response.data.id,
                          projectid: nextSub.projectid,
                          pmsid: nextSub.pmsid
                        }).then(res => {
                          if (res.code == 200) {
                            this.msgSuccess('新增成功')
                            this.$emit('openChanged', true)
                          }
                        })
                      } else {
                        this.msgError(response.msg)
                        this.$emit('loadingClose')
                      }
                    })
                    .catch(error => {
                      // this.msgError(response.msg);
                      this.$emit('loadingClose')
                    })
                } else {
                  addData(route, this.form)
                    .then(response => {
                      if (response.code === 200) {
                        this.msgSuccess('新增成功')
                        this.$emit('openChanged', true)
                      }
                    })
                    .catch(reject => {
                      this.$emit('loadingClose')
                    })
                }
              }
            }
          }
        })
      } else {
        this.msgError('缺少链接！')
      }
    },
    apply() {
      var route = this.addurl
      if (route) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.docIds.length > 0) {
              this.form.docIds = this.docIds.join(',')
            }
            if (this.imageSrc.length > 0) {
              const baseUrl = this.upload.url
              let prop = this.addform.filter(
                item => item.componentType === 'image'
              )[0].prop
              this.form[prop] = []
              for (let index in this.image) {
                let formData = new FormData()
                let item = this.image[index]
                formData.append('file', item, item.name)
                axios
                  .post(baseUrl, formData, {
                    responseType: 'json',
                    headers: {
                      Authorization: 'Bearer ' + getToken(),
                      'Content-Type': 'multipart/form-data'
                    }
                  })
                  .then(response => {
                    this.form[prop].push({
                      fileName: item.name,
                      path: response.data.fileName,
                      fileSize: item.size
                    })
                    if (index == this.image.length - 1) {
                      this.form[prop] = JSON.stringify(this.form[prop])
                      addData(route, this.form).then(response => {
                        if (response.code === 200) {
                          this.msgSuccess('新增成功')
                          this.$emit('openChanged', true)
                        }
                      })
                    }
                  })
              }
              // axios
              //   .post(baseUrl, formData, {
              //     responseType: "json",
              //     headers: {
              //       Authorization: "Bearer " + getToken(),
              //       "Content-Type": "multipart/form-data",
              //     },
              //   })
              //   .then((response) => {
              //     this.form.thumb = response.data.fileName;
              //     addData(route, this.form).then((response) => {
              //       if (response.code === 200) {
              //         this.msgSuccess("新增成功");
              //         this.$emit("openChanged", true);
              //       }
              //     });
              //   });
            } else {
              addData(route, this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.hasapply = true
                  this.$forceUpdate()
                } else {
                  this.$emit('loadingClose')
                }
              })
            }
          }
        })
      } else {
        this.msgError('缺少链接！')
      }
    },
    handleSelectChange(prop) {
      this.$forceUpdate()
      //  this.selectChange(val,'');
      for (let item of this.addform) {
        if (item.show && item.show.indexOf(prop) > -1) {
          getDataList(item.show.replace(`{${prop}}`, this.form[prop])).then(
            response => {
              if (response.code == 200) {
                item.optionValue = response.rows
              }
            }
          )
        }
      }
    },
    handleChange(newV, oldV) {
      if (newV != undefined) {
        let optionData = JSON.parse(sessionStorage.getItem('optionsData'))
        let policyObj = optionData['policyOptions']
        let policyOptions = []
        policyObj.forEach(item => {
          if (item.typeIds) {
            if (item.typeIds.split(',').includes(newV.toString())) {
              policyOptions.push(item)
            }
          }
        })
        this.addform.forEach((item, index) => {
          if (item.prop === 'policyid') {
            // if (oldV) {
            //   this.form.policyid = '';
            //   this.form.stateid = '';
            // }
            this.addform[index].optionValue = policyOptions
            if (!this.form.stateid || oldV) {
              let oldV = this.form.policyid
              this.form.policyid = policyOptions[0].id
              this.selectChange(this.form.policyid, oldV)
            }
            // this.form.policyid = policyOptions[0].id
            // }
          }
        })
      }
    },
    selectChange(newV, oldV) {
      if (newV) {
        // this.stateid = 0
        let optionData = JSON.parse(sessionStorage.getItem('optionsData'))
        let policyObj = optionData['policyOptions']
        policyObj.forEach(item => {
          if (!this.form.id && item.id === newV) {
            this.form.revision = item.revision
          }
        })

        let stateObj = optionData['stateOptions']
        let stateOptions = []
        if (stateObj.length > 0) {
          stateObj.forEach(item => {
            if (item.policyid === newV) {
              stateOptions.push(item)
            }
          })
          stateOptions.sort((a, b) => {
            return a.sort - b.sort
          })
          if (stateOptions.length > 0) {
            this.addform.forEach((item, index) => {
              if (item.prop === 'stateid') {
                this.addform[index].optionValue = stateOptions
                if (!this.form.stateid || oldV) {
                  this.form.stateid = stateOptions[0].id
                }
              }
            })
          }
        }
      }
    },
    //粘贴上传图片
    onPasteUpload(event) {
      if (this.ready) {
        event.preventDefault()
        let items = event.clipboardData && event.clipboardData.items
        let file = null
        if (items && items.length) {
          // 检索剪切板items
          for (var i = 0; i < items.length; i++) {
            if (items[i].type.indexOf('image') !== -1) {
              file = items[i].getAsFile()
            }
          }
        }
        if (!file) {
          this.$message.info('无图片')
          return
        }
        let _this = this
        _this.image.push(file)
        if (window.FileReader) {
          var fr = new FileReader()
          fr.onloadend = function(e) {
            _this.imageSrc.push(e.target.result)
            _this.$forceUpdate()
          }
          fr.readAsDataURL(file)
        }
        this.fileNameList = this.fileNameList.concat(
          this.image.map(item => item.name)
        )
        this.copyFileNameList = deepClone(this.fileNameList)
        this.uploadProgressOpen = true
      }
    },
    drag(event) {
      var e = event || window.event
      e.preventDefault()
      e.stopPropagation()
    },
    dragEnd(event) {
      let _this = this
      var e = event || window.event
      e.preventDefault()
      e.stopPropagation()
      const files = new Array(e.dataTransfer.files)
      for (let file of files[0]) {
        if (file.type.indexOf('image') != '-1') {
          _this.image.push(file)
          if (window.FileReader) {
            var fr = new FileReader()
            fr.readAsDataURL(file)
            fr.onloadend = e => {
              _this.imageSrc.push(e.target.result)
              _this.$forceUpdate()
            }
          }
        }
      }
      this.fileNameList = this.fileNameList.concat(
        this.image.map(item => item.name)
      )
      this.copyFileNameList = deepClone(this.fileNameList)
      this.uploadProgressOpen = true
    },
    handleImageChange(event) {
      let _this = this
      for (let file of event.target.files) {
        _this.image.push(file)
        if (window.FileReader) {
          var fr = new FileReader()
          fr.readAsDataURL(file)
          fr.onloadend = e => {
            _this.imageSrc.push(e.target.result)
            _this.$forceUpdate()
          }
        }
        this.fileNameList = this.fileNameList.concat(
          this.image.map(item => item.name)
        )
        this.copyFileNameList = deepClone(this.fileNameList)
        this.uploadProgressOpen = true
      }
    },
    removeB64(index) {
      this.imageSrc.splice(index, 1)
      this.image.splice(index, 1)
      this.$forceUpdate()
      // console.log(this.imageSrc,this.image)
    },
    removeImg(item, index, prop) {
      // filedel({ fileList: [{ path: item.path }] }).then((response) => {
      //   this.msgSuccess("已删除");
      // });
      let temp = JSON.parse(this.form[prop])
      temp.splice(index, 1)
      this.form[prop] = JSON.stringify(temp)
      this.$forceUpdate()
    },
    handleReset() {
      this.fileNameList = this.image.map(item => item.name)
      this.reName = false
    },
    handleCancelRename() {
      this.fileNameList = deepClone(this.copyFileNameList)
      this.reName = false
    },
    imgPreview(url) {
      const newwin = window.open(
        '/imgPreview',
        createUniqueString(),
        `height=${
          0.5 * this.app.screenHeight > 600 ? 0.5 * this.app.screenHeight : 600
        },
                                    width=${
                                      0.5 * this.app.screenWidth > 960
                                        ? 0.5 * this.app.screenWidth
                                        : 960
                                    },
                                    top=${0.2 * this.app.screenHeight},
                                    left=${0.2 * this.app.screenWidth}`
      )
      newwin.imgs = url
    },
    addExisting(item) {
      let pageParams = eval('(' + item.show + ')')
      this.table = pageParams.table
      this.formtype = pageParams.type
      // if(pageParams.defaultSelect){
      //   let arr = pageParams.defaultSelect.split('-');
      //   this.defaultSelect[arr[0]]=this.selected[0][arr[1]].split(',');
      // }else{
      //   this.defaultSelect = {}
      // }
      this.expandUrl = pageParams.expandUrl
      if (pageParams.search != undefined) this.search = pageParams.search
      this.geturl = this.getUrl(pageParams.getUrl)
      this.title = item.name
      this.current = item
      this.topen = true
      this.defaultSelect = { id: [this.form[item.prop]] }
      // console.log(this.form[item.prop])
      // this.geturl = item.show
      this.formMulti = pageParams.formMulti
    },
    topenChanged() {
      this.topen = false
    },
    handleSubmitAddExisting(val) {
      // console.log(val)
      if (
        !(this.current.optionValue instanceof Array) ||
        this.current.optionValue.length == 1
      )
        this.current.optionValue = val
      this.form[this.current.prop] = val.map(item => item.id)[0].toString()
      // this.form[this.current.prop+"ShowName"] = val.map(item=>item.name)[0]
      this.topen = false
    }
  }
}
</script>
<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
.el-checkbox.el-checkbox__label {
  width: 100%;
}
// /deep/.el-upload-dragger{
//   width: 100px;
//   height: 47px;
// }
.pasteImg {
  width: 100px;
  height: 47px;
  background: grey;
  text-align: center;
  line-height: 23px;
  float: left;
  color: cornsilk;
  font-size: 10px;
  position: relative;
}
.right {
  float: right;
}
.btn {
  padding: 0 5px;
}
.detail-title {
  width: 100px;
  padding: 5px 2px;
  display: block;
  background-color: #f5f7fa;
}
.detail-content {
  padding: 5px 2px;
  display: inline-block;
}
</style>
